import json

from django.db.models import Q
from django.http import JsonResponse
from django.shortcuts import render

# Create your views here.
from haystack.generic_views import SearchView
from rest_framework.generics import ListAPIView, GenericAPIView
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from rest_framework.views import APIView

# from activity.serializers import EnterpriseSerializer
from recruit.models import Recruit, Enterprise, City
from recruit.serialziers import RecruitSerializer,  RecruitInfoSerializer, RecuitModelSerialzier, \
    HotCitySerializer,EnterpriseSerializer


class EnterpriseModelView(APIView):
    """企业详情页"""

    def get(self, request, id):
        enter_prise = Enterprise.objects.filter(id=id)
        serializer = EnterpriseSerializer(enter_prise, many=True)
        return Response(serializer.data[0])


#  推荐职位
class RecruitAPIView(ListAPIView):
    queryset = Recruit.objects.all().order_by('-visits')[0:4]
    serializer_class = RecruitSerializer


#  最新职位
class RecruitNewAPIView(ListAPIView):
    queryset = Recruit.objects.all().order_by('-createtime')[0:4]
    serializer_class = RecruitSerializer


#  热门企业
class EnterpriseHowAPIView(ListAPIView):
    queryset = Enterprise.objects.all().order_by('-visits')[0:4]
    serializer_class = EnterpriseSerializer


# 获取职位详情
class RecruitInfoView(GenericAPIView):
    # queryset = Enterprise.objects.all()
    serializer_class = RecruitInfoSerializer
    lookup_field = 'id'

    def get(self, request, id):
        query_set = Recruit.objects.filter(id=id)
        serializer = self.get_serializer(query_set, many=True)
        return Response(serializer.data[0])


# 职位增加访问量
class UpdateVisitsView(APIView):

    def put(self, request, id):
        query_set = Recruit.objects.filter(id=id).first()
        if query_set:
            query_set.visits += 1
            query_set.save()
            return Response({"message": "更新成功", "success": True})

        else:
            return Response({"message": "没有找到数据", "success": False})


class CollectEnterpriceView(APIView):
    """收藏企业与取消收藏(没写验证)"""

    # authentication_classes = [IsAuthenticated]
    def post(self, request, id):
        try:
            # user_detial = Enterprise.objects.get(users_id=request.user.id)
            user_detial = Enterprise.objects.filter(users__id=request.user.id).first()
            if user_detial:
                return Response({"message": "已收藏成功", "success": True})
            else:
                detial = Enterprise.objects.filter(id=id).first()
                detial.users.add(request.user)
                detial.save()
                return Response({"message": "收藏成功", "success": True})
        except Exception as e:
            return Response({"errno": '数据库出错'})


class CollectEnterpriceViewS(APIView):
    """收藏企业与取消收藏(没写验证)"""

    # authentication_classes = [IsAuthenticated]
    def post(self, request, id):
        try:
            # user_detial = Enterprise.objects.get(users_id=request.user.id)
            user_detial = Enterprise.objects.filter(users__id=request.user.id).first()
            if user_detial:
                user_detial.users.remove(request.user)
                user_detial.save()
                return Response({"message": "取消收藏成功", "success": True})
            else:
                return Response({"message": "已取消收藏成功", "success": True})
        except Exception as e:
            return Response({"errno": '数据库出错'})


class CollectRecruitsView(APIView):
    """收藏职位与取消收藏(没写验证)"""

    def post(self, request, id):

        try:
            user_detial = Recruit.objects.filter(users__id=request.user.id).first()
            if user_detial:
                return Response({"message": "已收藏成功", "success": True})
            else:
                detial = Recruit.objects.filter(id=id).first()
                detial.users.add(request.user)
                detial.save()
                return Response({"message": "收藏成功", "success": True})
        except Exception as e:
            return Response({"errno": '数据库出错'})


class CollectRecruitsViewS(APIView):
    """收藏职位与取消收藏(没写验证)"""

    def post(self, request, id):

        try:
            user_detial = Recruit.objects.filter(users__id=request.user.id).first()
            if user_detial:
                user_detial.users.remove(request.user)
                user_detial.save()
                return Response({"message": "取消收藏成功", "success": True})
            else:
                return Response({"message": "已取消收藏成功", "success": True})
        except Exception as e:
            return Response({"errno": '数据库出错'})


class VisitAddView(APIView):
    """增加企业访问次数"""

    def put(self, request, id):
        try:
            enter_prise = Enterprise.objects.get(id=id)
            enter_prise.visits += 1
            enter_prise.save()
        except Exception as e:
            return Response({
                "errno": "数据库出错"
            })
        else:
            return Response({"message": "更新成功", "success": True})


class HotCityView(APIView):
    """热门城市"""

    def get(self, request):
        hot_city = City.objects.filter(ishot=1)
        serializer = HotCitySerializer(hot_city, many=True)
        return Response(serializer.data)

# 搜索职位
class SearchRecruitsView(ListAPIView):

    serializer_class = RecuitModelSerialzier

    def get_queryset(self):

        keyword = self.request.data.get('keyword')
        cityname = self.request.data.get('cityname')

        if not keyword:
            recruite = Recruit.objects.filter(city=cityname)
        else:
            recruite = Recruit.objects.filter(Q(city=cityname) &
                                              Q(jobname__contains=keyword))

        return recruite

    def post(self, request, *args, **kwargs):
        return self.list(request, *args, **kwargs)







# class SerachRecruitsView(SearchView):
#     """搜索职位"""
#     def create_response(self):
#         name_keyword = json.loads(self.request.body.decode())
#         name = name_keyword.get('cityname')
#         keyword = name_keyword.get('keyword')
#         # 获取搜索结果
#         context = self.get_context()
#         data_list = []
#         for recryuts in context['page'].object_list:
#             retruits_new = [recryuts.object.enterprise_id]
#             enterprice_dict = {"id": recryuts.object.enterprise.id, "name_new": recryuts.object.enterprise.name,
#                                "labels": recryuts.object.enterprise.labels, "logo": recryuts.object.enterprise.logo,
#                                "summary": recryuts.object.enterprise.summary, "retruits": retruits_new}
#
#             data_list.append({
#                 "id": recryuts.object.id,
#                 'jobname': recryuts.object.jobname,
#                 'condition': recryuts.object.condition,
#                 'education': recryuts.object.education,
#                 'type': recryuts.object.type,
#                 'city': recryuts.object.city,
#                 'salary': recryuts.object.salary,
#                 'createtime': recryuts.object.createtime,
#                 'enterprise': enterprice_dict,
#                 'lables': recryuts.object.lables,
#             })
#
#         return JsonResponse(data_list, safe=False)